// API工具类
class ApiClient {
    constructor() {
        this.baseURL = '/api';
        this.token = localStorage.getItem('jwt_token') || '';
    }

    // 设置令牌
    setToken(token) {
        this.token = token;
        if (token) {
            localStorage.setItem('jwt_token', token);
        } else {
            localStorage.removeItem('jwt_token');
        }
    }

    // 获取请求头
    getHeaders() {
        const headers = {
            'Content-Type': 'application/json'
        };

        if (this.token) {
            headers['Authorization'] = `Bearer ${this.token}`;
        }

        return headers;
    }

    // 通用请求方法
    async request(url, options = {}) {
        const config = {
            headers: this.getHeaders(),
            ...options
        };

        try {
            const response = await fetch(`${this.baseURL}${url}`, config);
            const data = await response.json();

            // 处理认证失败
            if (response.status === 401) {
                this.handleAuthError();
                throw new Error('认证失败，请重新登录');
            }

            return data;
        } catch (error) {
            console.error('API请求失败:', error);
            throw error;
        }
    }

    // 处理认证错误
    handleAuthError() {
        this.setToken('');
        // 触发全局事件，让应用跳转到登录页
        window.dispatchEvent(new CustomEvent('auth-error'));
    }

    // GET请求
    async get(url, params = {}) {
        const queryString = new URLSearchParams(params).toString();
        const fullUrl = queryString ? `${url}?${queryString}` : url;
        return this.request(fullUrl);
    }

    // POST请求
    async post(url, data = {}) {
        return this.request(url, {
            method: 'POST',
            body: JSON.stringify(data)
        });
    }

    // PUT请求
    async put(url, data = {}) {
        return this.request(url, {
            method: 'PUT',
            body: JSON.stringify(data)
        });
    }

    // DELETE请求
    async delete(url) {
        return this.request(url, {
            method: 'DELETE'
        });
    }

    // 用户相关API
    async register(userData) {
        return this.post('/user/register', userData);
    }

    async login(credentials) {
        const response = await this.post('/user/login', credentials);
        if (response.code === 200 && response.data.token) {
            this.setToken(response.data.token);
        }
        return response;
    }

    async updateUserProfile(userId, userData) {
        return this.put(`/user/${userId}`, userData);
    }

    async getUserProfile(userId) {
        return this.get(`/user/${userId}`);
    }

    // 分类相关API
    async getCategories() {
        return this.get('/category/tree');
    }

    async getCategoryTree() {
        return this.get('/category/tree');
    }

    async createCategory(categoryData) {
        return this.post('/category/', categoryData);
    }

    async updateCategory(id, categoryData) {
        return this.put(`/category/${id}`, categoryData);
    }

    async deleteCategory(id) {
        return this.delete(`/category/${id}`);
    }

    async searchCategories(keyword, page = 1, pageSize = 10) {
        return this.get('/category/search', {
            keyword,
            page,
            page_size: pageSize
        });
    }

    // 收藏相关API
    async getBookmarks(params = {}) {
        return this.get('/bookmark/', params);
    }

    async getBookmark(id) {
        return this.get(`/bookmark/${id}`);
    }

    async createBookmark(bookmarkData) {
        return this.post('/bookmark/', bookmarkData);
    }

    async updateBookmark(id, bookmarkData) {
        return this.put(`/bookmark/${id}`, bookmarkData);
    }

    async deleteBookmark(id) {
        return this.delete(`/bookmark/${id}`);
    }

    async getBookmarksByCategory(categoryId) {
        return this.get(`/bookmark/category/${categoryId}`);
    }

    async batchOperateBookmarksAsync(operation) {
        return this.post('/bookmark/batch', operation);
    }

    async getURLPreview(url) {
        return this.get('/bookmark/preview', { url });
    }

    async visitBookmark(id) {
        return this.post(`/bookmark/${id}/visit`);
    }

    // 统计相关API
    async getStats() {
        try {
            const [categoriesRes, bookmarksRes] = await Promise.all([
                this.getCategories(),
                this.getBookmarks()
            ]);

            return {
                categories: categoriesRes.code === 200 ? categoriesRes.data : [],
                bookmarks: bookmarksRes.code === 200 ? bookmarksRes.data : [],
                totalCategories: categoriesRes.code === 200 ? categoriesRes.data.length : 0,
                totalBookmarks: bookmarksRes.code === 200 ? bookmarksRes.data.length : 0
            };
        } catch (error) {
            console.error('获取统计数据失败:', error);
            return {
                categories: [],
                bookmarks: [],
                totalCategories: 0,
                totalBookmarks: 0
            };
        }
    }
}

// 创建全局API实例
window.api = new ApiClient();

// 工具函数
const utils = {
    // 显示消息提示
    showMessage(message, type = 'info', duration = 3000) {
        // 触发全局消息事件
        window.dispatchEvent(new CustomEvent('show-message', {
            detail: { message, type, duration }
        }));
    },

    // 格式化日期
    formatDate(date) {
        if (!date) return '';
        const d = new Date(date);
        return d.toLocaleDateString('zh-CN', {
            year: 'numeric',
            month: '2-digit',
            day: '2-digit',
            hour: '2-digit',
            minute: '2-digit'
        });
    },

    // 格式化URL
    formatURL(url) {
        if (!url) return '';
        if (!url.startsWith('http://') && !url.startsWith('https://')) {
            return 'https://' + url;
        }
        return url;
    },

    // 获取域名
    getDomain(url) {
        try {
            const urlObj = new URL(this.formatURL(url));
            return urlObj.hostname;
        } catch {
            return url;
        }
    },

    // 截断文本
    truncateText(text, maxLength = 50) {
        if (!text) return '';
        if (text.length <= maxLength) return text;
        return text.substring(0, maxLength) + '...';
    },

    // 防抖函数
    debounce(func, wait) {
        let timeout;
        return function executedFunction(...args) {
            const later = () => {
                clearTimeout(timeout);
                func(...args);
            };
            clearTimeout(timeout);
            timeout = setTimeout(later, wait);
        };
    },

    // 节流函数
    throttle(func, limit) {
        let inThrottle;
        return function() {
            const args = arguments;
            const context = this;
            if (!inThrottle) {
                func.apply(context, args);
                inThrottle = true;
                setTimeout(() => inThrottle = false, limit);
            }
        };
    },

    // 验证邮箱
    validateEmail(email) {
        const re = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
        return re.test(email);
    },

    // 验证URL
    validateURL(url) {
        try {
            new URL(this.formatURL(url));
            return true;
        } catch {
            return false;
        }
    },

    // 生成随机ID
    generateId() {
        return Math.random().toString(36).substr(2, 9);
    },

    // 复制到剪贴板
    async copyToClipboard(text) {
        try {
            await navigator.clipboard.writeText(text);
            this.showMessage('已复制到剪贴板', 'success');
        } catch (error) {
            console.error('复制失败:', error);
            this.showMessage('复制失败', 'error');
        }
    },

    // 下载文件
    downloadFile(content, filename, type = 'text/plain') {
        const blob = new Blob([content], { type });
        const url = URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = filename;
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
        URL.revokeObjectURL(url);
    },

    // 获取文件图标
    getFileIcon(url) {
        const domain = this.getDomain(url);
        return `https://www.google.com/s2/favicons?domain=${domain}&sz=32`;
    }
};

// 将工具函数挂载到全局
window.utils = utils;
